package chat7me_1223.server.dao;

import chat7me_1223.server.utils.DBUtils;
import chat7me_1223.server.vo.UserData;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    public static   synchronized  void addUser(UserData userData){
        PreparedStatement stmt=null;
        try {
            if(isExists(userData.getUsername())){
                throw  new RuntimeException("用户名被占用");
            }
            Connection conn= DBUtils.getConnection();
            stmt=conn.prepareStatement(
                    "insert into char_user(username,password)value(?,?)");
            stmt.executeUpdate();
        }catch (SQLException e){
            throw  new RuntimeException("注册异常");
        }finally {
            try {
                stmt.close();
                DBUtils.closeConnection();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }
    }

    public static  boolean  isExists(String username) throws  SQLException{
        try {
            Connection conn=DBUtils.getConnection();
            PreparedStatement stmt = conn.prepareStatement("select * from char_user where username=?");
            ResultSet rs=stmt.executeQuery();
            if(rs.next()){
                return true;
            }else{
                return false;
            }
        }catch(SQLException e){
            throw  e;
        }finally {
            DBUtils.closeConnection();
        }
    }


    public static  boolean  login(UserData user) throws SQLException {
        try {
            Connection conn=DBUtils.getConnection();
            PreparedStatement stmt = conn.prepareStatement("select * from char_user where username=? and  password=?");
            stmt.setString(1,user.getUsername());
            stmt.setString(2,user.getPassword());
            ResultSet rs=stmt.executeQuery();
            if(rs.next()){
                return true;
            }else{
                return false;
            }
        }catch(SQLException e){
            throw  e;
        }finally {
            DBUtils.closeConnection();
        }
    }



}
